# encoding=utf-8
import requests

from framework.response import Response
from framework.common.pt_logger import logger


class Request(object):
    def __init__(self, method="GET"):
        self.middleware_list = []
        self.method = method
        self.raw_url = None
        self.url = None
        self.proxies = None
        self.header = None

    def request(self, url):
        self.url = url
        self.raw_url = url
        for m in self.middleware_list:
            m._set_request(self)
        logger.info("raw url: %s" % self.raw_url)
        logger.info("request to %s" % self.url)
        rsp = requests.request(self.method, self.url, proxies=self.proxies, timeout=45, headers=self.header)
        response = Response(rsp.url, rsp.status_code, rsp.encoding, rsp.content)
        response.raw_url = url
        logger.info("status code: %s" % response.status_code)
        return response

    def middleware(self, middleware):
        self.middleware_list.append(middleware)
        return self
